<?php

require_once('persistence/AbstractGenericDao.class.php');
require_once('persistence/IUserDao.class.php');

define('_SQL_FETCH_USERS', 'SELECT user_id, username FROM ' . TBL_USER);
define('_SQL_VALIDATE_USER', 'SELECT user_id FROM ' . TBL_USER . ' WHERE username=:username AND password=:password');

define('_SQL_CHECK_USERNAME', 'SELECT COUNT(*) AS cnt FROM ' . TBL_USER . ' WHERE username=:username');
define('_SQL_INSERT_USER', 'INSERT INTO ' . TBL_USER . ' (username, password, email) VALUES (:username, :password, :email)');

class GenericUserDao extends AbstractGenericDao implements IUserDao {

	public function GenericUserDao($db) {
		parent::__construct($db);
	}
	
	public function fetchUsers() {
		Log::instance()->debug("Invoking fetchUsers()");
		return $this->dbQuery(_SQL_FETCH_USERS);
	}
	
	public function validateUser($username, $password) {
		Log::instance()->debug("Invoking validateUser(username=$username;password=$password)");
		
		$stmt = $this->prepareStatement(_SQL_VALIDATE_USER);
		$stmt->bindParam(':username', $username, PDO::PARAM_STR);
		$stmt->bindParam(':password', $password, PDO::PARAM_STR);
		$stmt->execute();
		$rows = $stmt->fetchAll();
		
		if(sizeof($rows) == 0) {
			Log::instance()->debug("Invalid username/password.");
			return -1;
		}
		
		Log::instance()->debug("User could be successfully validated.");
		return $rows[0]['user_id'];
	}
	
	public function addUser($username, $password, $email) {
		Log::instance()->debug("Invoking addUser(username=$username;password=$password;email=$email)");
		
		$stmt = $this->prepareStatement(_SQL_CHECK_USERNAME);
		$stmt->bindParam(':username', $username, PDO::PARAM_STR);
		$stmt->execute();
		$rows = $stmt->fetchAll();
		$cnt = $rows[0]['cnt'];
		
		if($cnt != 0) {
			Log::instance()->debug("Try to register already used username [$username].");
			return -1;
		}
		
		$stmt = $this->prepareStatement(_SQL_INSERT_USER);
		$stmt->bindParam(':username', $username, PDO::PARAM_STR);
		$stmt->bindParam(':password', $password, PDO::PARAM_STR);
		$stmt->bindParam(':email', $email, PDO::PARAM_STR);
		$stmt->execute();
		
		$lastUserId = $this->lastInsertId();
		Log::instance()->debug("Successfully inserted user [$username] with id [$lastUserId].");
		return $lastUserId;
	}
}

?>